package cn.gary.oaserver.service.impl;

import cn.gary.oaserver.entity.TDepartment;
import cn.gary.oaserver.mapper.TDepartmentMapper;
import cn.gary.oaserver.service.ITDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gary
 * @since 2024-03-15
 */
@Service
public class TDepartmentServiceImpl extends ServiceImpl<TDepartmentMapper, TDepartment> implements ITDepartmentService {

    @Override
    public List<TDepartment> getAllDepartments() {
        List<TDepartment> list = this.list ( );
        List<TDepartment> allList = list.stream ( ).filter ( dept -> dept.getParentId ( ) == -1 ).map ( dept -> {
            dept.setChildren ( getChildren ( dept.getId ( ), list ) );
            return dept;
        } ).collect ( Collectors.toList ( ) );
        return allList;
    }

    private List<TDepartment> getChildren(Integer id, List<TDepartment> list) {
        return list.stream ( ).filter ( dept -> id.intValue ( ) == dept.getParentId ( ) ).map ( dept -> {
            dept.setChildren ( getChildren ( dept.getId (),list ) );
            return dept;
        } ).collect ( Collectors.toList() );
    }
}
